package com.swift.base;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.swift.R;
import com.swift.utils.ActivityUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.List;


public class ActivityBase extends AppCompatActivity {
	protected final String TAG = ActivityBase.class.getName();
	public final static int RIGHT_BUTTON_NONE = 0;
	public final static int RIGHT_BUTTON_SEARCH = 1;
	public final static int RIGHT_BUTTON_OTHER = 2;
	
	private EditText mEdtSearchInput;
	private SearchTextWatcher mSearchTextWatcher;
	private ViewGroup mActionbar;
	
	public static Context context; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		super.onCreate(savedInstanceState);
		StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		context = getBaseContext();
		ActivityUtil.getInstances().add(this);
		LogClassName();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
//		JPushInterface.onResume(this);
		MobclickAgent.onResume(this);
	}
	
	@Override
	protected void onPause() {
//		JPushInterface.onPause(this);
		MobclickAgent.onPause(this);
		super.onPause();
	}


		
	class SearchTextWatcher implements TextWatcher{

		private SearchHander mSearchHander;
		
	    public SearchTextWatcher(ActivityBase activity) {
	    	mSearchHander = new SearchHander(activity);
		}
		@Override
		public void beforeTextChanged(CharSequence paramCharSequence,
				int paramInt1, int paramInt2, int paramInt3) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub			
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			mSearchHander.sendMessageDelayed(mSearchHander.obtainMessage(0,  System.currentTimeMillis()), SearchHander.DELAY_PERIOD);
		}

	}
	
	
	
	private static class SearchHander extends Handler{
		private ActivityBase mActivityBase;
		private long mLastTextChangedTime;
		public final static long DELAY_PERIOD = 1000; 
		
		public  SearchHander(ActivityBase activity) {
			mActivityBase= activity;
			mLastTextChangedTime = 0;
		}
		 @Override
	        public void handleMessage(Message msg) {
	            // TODO Auto-generated method stub
	            super.handleMessage(msg);
	            if (msg.obj != null){
	            	long sendTime =  (Long)msg.obj ;
	            	long timeDiff = sendTime - mLastTextChangedTime ;
	            	if (timeDiff > SearchHander.DELAY_PERIOD){	      	
	            		mActivityBase.search();
	            	}
	            	mLastTextChangedTime = sendTime;     
	            }
	        }
	}

	private void search() {			
		if (mEdtSearchInput!= null){
			onSearch(mEdtSearchInput.getText().toString());
		}
	}
	
	protected void onSearch(String text){
		
	}
	
	protected void onRightButtonClick(View view){
		
	}
	protected void onBackButtonClick(View v) {
		finish();
	}
	
	private TextView mTitle = null;
	private ImageView mBtnBack;

	
	/**   
	 * @author: HYM 
	 * @Title: LogClassName   
	 * @Description: TODO(输出当前activity的类名)   
	 * @param:       
	 * @return: void       
	 * @throws   
	 */  
	void LogClassName()
	{
		ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rtiList = am.getRunningTasks(1);
		RunningTaskInfo runningTaskInfo = rtiList.get(0);
		ComponentName componentName = runningTaskInfo.topActivity;
		Log.i(TAG, componentName.getClassName());
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: toast   
	 * @Description: TODO(Toast一些信息)   
	 * @param: @param text      
	 * @return: void       
	 * @throws   
	 */  
	protected void toast(String text)
	{
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	
	/**   
	 * @author: HYM 
	 * @Title: toast   
	 * @Description: TODO(Toast一些信息)   
	 * @param: @param string      
	 * @return: void       
	 * @throws   
	 */  
	protected void toast(int string)
	{
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: showDialog   
	 * @Description: TODO(显示一个进度条)   
	 * @param: @param dialog
	 * @param: @param text      
	 * @return: void       
	 * @throws   
	 */  
	protected Dialog showDialog(Dialog dialog,String text)
	{
		if (TextUtils.isEmpty(text)) {
			//得到加载的提示
			text = getResources().getString(R.string.loading_text);
		}
		
		if (null == dialog) {
			dialog = ProgressDialog.show(this, null , text, true);
			dialog.setCancelable(true);
		}
		if(null != dialog && !dialog.isShowing())
			dialog.show();
		return dialog;
	}
	
	protected Dialog showDialog(Dialog dialog)
	{
		return showDialog(dialog,null);
	}
	
	 
	/**   
	 * @author: HYM 
	 * @Title: hideDialog   
	 * @Description: TODO(隐藏一个进度条)   
	 * @param: @param dialog      
	 * @return: void       
	 * @throws   
	 */  
	protected void hideDialog(Dialog dialog)
	{
		if(null != dialog && dialog.isShowing())
			dialog.dismiss();
	}
	
	protected void setTop(String title,boolean isDeclare,boolean isSearch) {
		setTop(title,null,null,isDeclare,isSearch,getDefDeclareDraw(),getDefSearchDraw());
	}
	
	protected void setTop(String title,boolean isDeclare,boolean isSearch,Drawable declareDraw,Drawable searchDraw) {
		setTop(title,null,null,isDeclare,isSearch,declareDraw,searchDraw);
	}
	
	/**   
	 * @author: HYM 
	 * @Title: setTop   
	 * @Description: TODO(设置头部菜单)   
	 * @param: @param title
	 * @param: @param declare
	 * @param: @param search
	 * @param: @param isDeclare
	 * @param: @param isSearch
	 * @param: @param declareDraw
	 * @param: @param searchDraw      
	 * @return: void    
	 * @return: 2017-5-8
	 * @throws   
	 */  
	protected void setTop(String title,String declare,String search,boolean isDeclare,boolean isSearch, Drawable declareDraw, Drawable searchDraw) {
		mActionbar = (ViewGroup) findViewById(R.id.top_layout);
		if (mActionbar != null){
			TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
			tvTitle.setText(TextUtils.isEmpty(title) ? getResources().getString(R.string.back) : title);
			
			TextView tvDeclare = (TextView) findViewById(R.id.tvDeclare);
			if (!isDeclare) {
				tvDeclare.setVisibility(View.GONE);
			}
			else {
				tvDeclare.setText(TextUtils.isEmpty(declare) ? getResources().getString(R.string.declare) : declare);
				if (declareDraw != null) {
					declareDraw.setBounds(0, 0, declareDraw.getMinimumWidth(), declareDraw.getMinimumHeight());
				}
				tvDeclare.setCompoundDrawables(declareDraw, null, null, null);
				
			}
			
			TextView tvSearch = (TextView) findViewById(R.id.tvSearch);
			if (!isSearch) {
				tvSearch.setVisibility(View.GONE);
			}
			else {
				tvSearch.setText(TextUtils.isEmpty(search) ? getResources().getString(R.string.query) : search);
				if (searchDraw != null) {
					searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(), searchDraw.getMinimumHeight());
				}
				tvSearch.setCompoundDrawables(searchDraw, null, null, null);
			}
			
		}
	}
	
	protected Drawable getDefDeclareDraw() {
		return getResources().getDrawable(R.drawable.icon_report);
	}
	protected Drawable getDefSearchDraw() {
		return getResources().getDrawable(R.drawable.icon_search);
	}
	
//	public boolean onTouchEvent(MotionEvent event) {
//		if (null != this.getCurrentFocus()) {
//			/**
//			 * 点击空白位置 隐藏软键盘
//			 */
//			InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
//			return mInputMethodManager.hideSoftInputFromWindow(this
//					.getCurrentFocus().getWindowToken(), 0);
//		}
//		return super.onTouchEvent(event);
//	}
	
	@Override  
	public boolean dispatchTouchEvent(MotionEvent ev) {  
	    if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
	        View v = getCurrentFocus();  
	        if (isShouldHideInput(v, ev)) {  
	  
	            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
	            if (imm != null) {  
	                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
	            }  
	        }  
	        return super.dispatchTouchEvent(ev);  
	    }  
	    // 必不可少，否则所有的组件都不会有TouchEvent了  
	    if (getWindow().superDispatchTouchEvent(ev)) {  
	        return true;  
	    }  
	    return onTouchEvent(ev);  
	}  
	
	public  boolean isShouldHideInput(View v, MotionEvent event) {  
	    if (v != null && (v instanceof EditText)) {  
	        int[] leftTop = { 0, 0 };
			//获取输入框当前的location位置
			v.getLocationInWindow(leftTop);
			int left = leftTop[0];
	        int top = leftTop[1];  
	        int bottom = top + v.getHeight();  
	        int right = left + v.getWidth();  
	        if (event.getRawX() > left && event.getRawX() < right  
	                && event.getRawY() > top && event.getRawY() < bottom) {  
	            // 点击的是输入框区域，保留点击EditText的事件  
	            return false;  
	        } else {  
	            return true;  
	        }  
	    }  
	    return false;  
	}  
	
	/**   
	 * @author: HYM 
	 * @Title: getResStringByResId   
	 * @Description: TODO(根据id获取res string的字符串)   
	 * @return String 
	 * @date: 2017-5-11
	 */  
	public String getResStringByResId(int id)
	{
		return getResources().getString(id);
	}
}
